/**
 *   Copyright (c) fanguangping. All rights reserved.
 *   The use and distribution terms for this software are covered by the
 *   Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 *   which can be found in the file epl-v10.html at the root of this distribution.
 *   By using this software in any fashion, you are agreeing to be bound by
 * 	 the terms of this license.
 *   You must not remove this notice, or any other, from this software.
 **/
package org.jfunny.core.meta;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.jfunny.core.util.FileUtil;

/**
 * 命名空间
 * @author fanguangping
 *
 */
public class Namespace {
	private String name;
	private File file;
	private String source;
	private Set<Namespace> used;
	private boolean templateSpace;

	public Namespace(String name) {
		super();
		this.name = name;
		this.used = new HashSet<Namespace>();
	}

	public void addUsedNamespace(Namespace ns) {
		this.used.add(ns);
	}

	//---- getters ----
	public String getName() {
		return name;
	}

	public File getFile() {
		return file;
	}

	public Set<Namespace> getUsed() {
		return used;
	}

	public boolean isTemplateSpace() {
		return templateSpace;
	}

	public String getSource() {
		if (source == null) {
			try {
				source = FileUtil.readTxt(file.getAbsolutePath());
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return source;
	}

	//---- setters ----
	public void setFile(File file) {
		this.file = file;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public void setTemplateSpace(boolean templateSpace) {
		this.templateSpace = templateSpace;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof Namespace)) {
			return false;
		}
		Namespace ns = (Namespace) obj;
		return (ns != null) && (ns.name != null) && ns.name.equals(name);
	}

	public int hashCode() {
		return (name == null) ? -1 : name.hashCode();
	}
	
	public String toString(){
		return name;
	}

	public static Namespace findNamespace(Set<Namespace> set, String nsName) {
		Namespace namespace = null;
		for (Namespace ns : set) {
			if (ns.getName().equals(nsName)) {
				namespace = ns;
			}
		}
		return namespace;
	}
}
